package dao

import models.Tables._
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.JdbcProfile

import javax.inject.{Inject, Singleton}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

@Singleton
class TestDao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends
  HasDatabaseConfigProvider[JdbcProfile] {


  import utils.MyPostgresProfile.api._

  type MyRow = TestRow
  val table = Test

  def insert(row: MyRow) = {
    db.run(table += row)
  }

  def insertAll(rows: List[MyRow]) = {
    db.run(table ++= rows)
  }

  def selectAll(ids: List[String]) = db.run(table.filter(_.sampleId.inSetBind(ids)).
    result.map(_.toList))

  def selectAll(company: String) = db.run(table.filter(_.company === company).
    result.map(_.toList))

  def selectAll = db.run(table.
    result.map(_.toList))

  def deleteAll(rows: List[MyRow]) = {
    val action = DBIO.sequence(
      rows.map { row =>
        table.filter(x => x.sampleId === row.sampleId && x.testType === row.testType && x.company === row.company).delete
      }
    ).transactionally
    db.run(action).map(_ => ())
  }

  def deleteAll(sampleId: String) = {
    val action = table.filter(_.sampleId === sampleId).delete
    db.run(action).map(_ => ())
  }

  def selectById(id: Int) = db.run(table.
    filter(_.id === id).result.head)

  def select(sampleId: String, testType: String, company: String) = db.run(table.
    filter(x => x.sampleId === sampleId && x.testType === testType && x.company === company).result.head)

  def update(row: MyRow): Future[Unit] = db.run(table.filter(_.id === row.id).update(row)).
    map(_ => ())


}
